package com.pzl.common;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dalvik.system.DexFile;

public class JumpUtil {

    private static JumpUtil instance = new JumpUtil();

    /**
     * 缓存各组件模块所有的activity class,在application初始化缓存所有
     */
    private Map<String, Class<? extends Activity>> classes;

    private Context context;

    private JumpUtil() {
        classes = new HashMap<>();
    }

    public void init(Context context) {
        instance.context = context;

        /**
         * 找到同一包名下所有的工具实现类，通过回调接口，把所有模块里面的activity class 缓存到容器
         */
        List<String> classPath = getClassName("com.pzl.path");
        for (String className : classPath) {
            try {
                Class<?> utilClass = Class.forName(className);
                if (IJump.class.isAssignableFrom(utilClass)) {
                    IJump iJump = (IJump) utilClass.newInstance();
                    iJump.saveActivityClass();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static JumpUtil getInstance() {
        return instance;
    }

    /**
     * 缓存activity class 类对象
     *
     * @param key 一般申明为唯一的路径
     * @param cls
     */
    public void saveActivityClass(String key, Class cls) {
        if (classes.containsKey(key)) return;
        classes.put(key, cls);
    }

    public Class<? extends Activity> getActivityClass(String key) {
        return classes.get(key);
    }

    /**
     * activity 跳转
     *
     * @param path
     */
    public void jump(String path) {
        Class activityClass = getActivityClass(path);
        Log.i("jinx", activityClass.getName());
        if (activityClass == null) {
            Toast.makeText(context, path + " 不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(context, activityClass);
        context.startActivity(intent);
    }


    /**
     * 通过包名获取这个包下面的所有的类名
     *
     * @param packageName
     * @return
     */
    private List<String> getClassName(String packageName) {
        List<String> classList = new ArrayList<>();
        try {
            //把当前应有的apk存储路径给dexFile
            DexFile df = new DexFile(context.getPackageCodePath());
            Enumeration<String> entries = df.entries();
            while (entries.hasMoreElements()) {
                String className = (String) entries.nextElement();
                if (className.contains(packageName)) {
                    classList.add(className);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return classList;
    }

}
